import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author LKQ
 * @date 2021/12/26 9:30
 * @description
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.findOcurrences2("alice is a good girl she is a good student", "a", "good"));
    }

    public String[] findOcurrences(String text, String first, String second) {
        String[] arr = text.split(" ");
        List<String> list = new ArrayList<>();
        int n = arr.length;
        for (int i = 0; i < n-2; i++) {
            if (arr[i].equals(first) && arr[i+1].equals(second) ) {
                list.add(arr[i+2]);
            }
        }
        String[] ans = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ans[i] = list.get(i);
        }
        return ans;
    }
    public String[] findOcurrences2(String text, String first, String second) {
        String[] arr = text.split(" ");
        int n = arr.length;
        int count = 0;
        for (int i = 0; i < n-2; i++) {
            if (arr[i].equals(first) && arr[i+1].equals(second) ) {
                arr[count++] = arr[i+2];
            }
        }
        return Arrays.copyOf(arr, count);
    }
}
